package com.coco.utils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * Title:MorningGreeting.java
 * Description:早安工具类
 * Author：CoCo
 * Date:2024/9/19
 * Version:1.0
 */
public class MorningGreeting {
    private static String url = "https://apis.tianapi.com/zaoan/index?key=你的APIKEY";
    private static List<String> zaoanList = new ArrayList<>();

    private static String name = "老婆";


    /**
     * 调用接口获得早安语句
     * @param key
     * @return
     */
    public static String getZaoan(String key) {
        //默认彩虹屁
        String str = "阳光落在屋里，爱你藏在心里";
        try {
            JSONObject jsonObject = JSONObject.parseObject(HttpUtil.getUrl(url+key).replace("XXX", name));
            if (jsonObject.getIntValue("code") == 200) {
//                str = jsonObject.getJSONArray("result").getJSONObject(0).getString("content");
                str = jsonObject.getObject("result", HashMap.class).get("content").toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str;
    }

    /**
     * 载入早安语句库
     */
    static {
        InputStream inputStream = MorningGreeting.class.getClassLoader().getResourceAsStream("static/jinju.txt");
        try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"))) {
            String str = "";
            String temp = "";
            while ((temp = br.readLine()) != null) {
                if (!StringUtils.isEmpty(temp)) {
//                    str = str + "\r\n" + temp;
                    str = (str + temp).replaceAll("\r\n","");
                } else {
                    zaoanList.add(str);
                    str = "";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getMorningGreeting() {
        Random random = new Random();
        return zaoanList.get(random.nextInt(zaoanList.size()));
//        return "积极的思考带来更多的快乐。";
    }


    public static void main(String[] args) {
        System.out.println(getMorningGreeting());
    }


}
